<template>
  <div class="app-container">
    <el-card class="scan-card">
      <template #header>
        <div class="card-header">
          <el-row class="mb-1" style="text-align: center">
            <el-col :span="24">
              <el-button v-if="!isScanning" type="primary" @click="scanTagCode">
                {{ $t("visitor.scanTag") }}
              </el-button>
            </el-col>
          </el-row>
        </div>
      </template>
      <div>
        <div id="reader" style="display: none; width: 100%" />
        <button v-if="isScanning" @click="stopScanning">{{ $t("common.stopScanning") }}</button>
      </div>

      <div class="mb-2">
        <el-form ref="iFormRef" :model="formData" :rules="rules">
          <el-form-item :label="$t('visitor.tagNo')" prop="tagNo">
            <el-input
              v-model="formData.tagNo"
              :placeholder="$t('common.plsInput') + $t('visitor.tagNo')"
            />
          </el-form-item>
          <el-form-item :label="$t('visitor.name')" prop="name">
            <el-input
              v-model="formData.name"
              :placeholder="$t('common.plsInput') + $t('visitor.name')"
            />
          </el-form-item>
          <el-form-item :label="$t('visitor.companyName')" prop="companyName">
            <el-input
              v-model="formData.companyName"
              :placeholder="$t('common.plsInput') + $t('visitor.companyName')"
            />
          </el-form-item>
          <el-form-item :label="$t('visitor.phone')" prop="phone">
            <el-input
              v-model="formData.phone"
              :placeholder="$t('common.plsInput') + $t('visitor.phone')"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-row class="mt-2" style="text-align: center">
          <el-col :span="12">
            <el-button size="large" @click="cancelBind">{{ $t("visitor.backTo") }}</el-button>
          </el-col>
          <el-col v-if="detailData.status == 0" :span="12">
            <el-button size="large" type="primary" @click="handleSubmit">
              {{ $t("common.confirm") }}
            </el-button>
          </el-col>
        </el-row>
      </template>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import qrcodeScanSound from "@/assets/qrcodescan.mp3";
import { Html5Qrcode } from "html5-qrcode";
import { ref } from "vue";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
defineOptions({
  name: "NoInviteForm",
  inheritAttrs: false,
});

const isScanning = ref<boolean>(false);
const html5QrCode = ref<Html5Qrcode | null>(null);

import VisitorAPI, { InvitePageVO, NoInviteForm } from "@/api/visitor/index";
const iFormRef = ref(ElForm);

const formData = reactive<NoInviteForm>({
  name: "",
  companyName: "",
  phone: "",
  tagNo: "",
  status: 1,
});

const detailData = reactive<InvitePageVO>({
  id: 0,
  visitorName: "",
  deptName: "",
  purposeName: "",
  planInAt: "",
  planOutAt: "",
  tagNo: "",
  actInAt: "",
  actOutAt: "",
  status: 0,
  opName: "",
});

function cancelBind() {
  formData.tagNo = "";
  formData.name = "";
  formData.companyName = "";
  formData.phone = "";
  stopScanning();
}

const rules = reactive({
  tagNo: [{ required: true, message: t("common.plsInput") + t("visitor.tagNo"), trigger: "blur" }],
  name: [{ required: true, message: t("common.plsInput") + t("visitor.name"), trigger: "blur" }],
  companyName: [
    { required: true, message: t("common.plsInput") + t("visitor.companyName"), trigger: "blur" },
  ],
  phone: [{ required: true, message: t("common.plsChoose") + t("visitor.phone"), trigger: "blur" }],
});

function handleSubmit() {
  if (formData.tagNo == "") {
    ElMessage.error(t("visitor.pleaseScanTagCode"));
    return;
  }

  iFormRef.value.validate((valid: boolean) => {
    if (valid) {
      formData.tagNo = formData.tagNo.slice(-6).toLocaleUpperCase();
      VisitorAPI.createNoInviteVisitor(formData)
        .then((res) => {
          if (res.data.code === 200) {
            ElMessage.success(res.data.message);
            formData.tagNo = "";
            formData.name = "";
            formData.companyName = "";
            formData.phone = "";
          } else {
            ElMessage.error(res.data.message);
          }
        })
        .catch((err) => {});
    }
  });
}

function scanTagCode() {
  startScanning("tag");
}

const startScanning = (type: string) => {
  html5QrCode.value = new Html5Qrcode("reader");
  isScanning.value = true;

  const readerElement = document.getElementById("reader");
  if (readerElement) {
    readerElement.style.display = "block";
  }

  html5QrCode.value
    .start(
      { facingMode: "environment" },
      {
        fps: 2, // Scan speed，2 times a second
        qrbox: 250,
      },
      (decoded: string) => {
        playSound();
        formData.tagNo = decoded.slice(-6).toLocaleUpperCase();
        stopScanning();
      },
      (err: any) => {
        isScanning.value = false;
      }
    )
    .catch((err: Error) => {
      isScanning.value = false;
    });
};

const stopScanning = () => {
  if (html5QrCode.value) {
    html5QrCode.value
      .stop()
      .then(() => {
        isScanning.value = false;
        html5QrCode.value = null;
        const readerElement = document.getElementById("reader");
        if (readerElement) {
          readerElement.style.display = "none";
        }
      })
      .catch((err: Error) => {});
  }
};

const playSound = () => {
  const audio = new Audio(qrcodeScanSound);
  audio.play().catch((error: Error) => {});
};
</script>

<style scoped>
.scan-card .el-card__header {
  background: #cdd0d6;
}
#reader video {
  width: 100%;
  height: 100%;
}
</style>
